
import 'dart:convert';

import 'package:flutter_book/data/model/yck/yck_rule_book_3_model.dart';

import 'db_helper.dart';

class YckRuleHelper{
  static YckRuleHelper? _helper;

  static YckRuleHelper init(){
    if(_helper==null){
      _helper=YckRuleHelper();
    }
    return _helper!;
  }

  static String tableName="YckRuleTable";
  static String yckRuleMode="YckRuleModel";
  static String yckRuleModelId="id";
  static String yckRuleModelTitle="title";
  static String yckRuleModelAddTime="addTime";


  Future<bool> update(YckRuleBook3Model? dto) async {
    if (dto == null || dto.id == null) {
      return false;
    }
    if (await isHave(dto.id!)) {
      return await _update(dto);
    } else {
      return await _insert(dto);
    }
  }

  Future<bool> _insert(YckRuleBook3Model? dto) async {
    if (dto == null) {
      return false;
    }
    var result = await DBHelper.instance.db.insert(tableName, toMap(dto));
    return result > 0;
  }

  Future<bool> _update(YckRuleBook3Model? dto) async {
    if (dto == null) {
      return false;
    }
    var result = await DBHelper.instance.db.update(tableName, toMap(dto), where: "$yckRuleModelId = '${dto.id}'");
    return result > 0;
  }

  Future<List<YckRuleBook3Model>> queryAll() async {
    List<YckRuleBook3Model> list = [];
    var result = await DBHelper.instance.db.query(tableName, orderBy: "$yckRuleModelAddTime desc");
    for (Map<String, dynamic> map in result) {
      list.add(YckRuleBook3Model.fromJson(json.decode(map[yckRuleMode]), map[yckRuleModelId]));
    }
    return list;
  }

  Future<Map<String, YckRuleBook3Model>> getAllMap() async {
    List<YckRuleBook3Model> list = await queryAll();
    Map<String, YckRuleBook3Model> dataMap = Map();
    list.forEach((element) {
      if (element.id == null) {
        return;
      }
      dataMap[element.id!] = element;
    });
    return dataMap;
  }

  Future<bool> isHave(String id) async {
    List<Map<String, dynamic>> result=[];
    result = await DBHelper.instance.db.query(tableName, where: "$yckRuleModelId = '$id'");
    return result.length > 0;
  }

  Future<void> clearAll() async {
    await DBHelper.instance.db.delete(tableName);
  }

  Future<void> remove(YckRuleBook3Model dto) async {
    await DBHelper.instance.db.delete(tableName, where: "$yckRuleModelId = '${dto.id}'");
  }


  Map<String, Object?> toMap(YckRuleBook3Model dto) {
    Map<String, Object?> map = Map();
    map[yckRuleModelId] = dto.id;
    map[yckRuleModelTitle] = dto.bookSourceName;
    map[yckRuleMode] = dto.toString();
    map[yckRuleModelAddTime] = dto.addTime;
    return map;
  }
}